package com.lzf.yh.commons;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * MD5工具类
 * @author 		Wyz
 * @createTime	2020年12月11日上午11:21:39
 */
public class MD5Util {
	
	/**
	 * 生成随机字符串（创建盐）
	 * @return
	 */
	public static String getSalt(){
		String string = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
		return string;
	}

	/**
	 * MD5加密方法
	 * @param source	需要加密的字符串
	 * @return
	 */
	public static String encrypt(String source) {
		return encodeMd5(source.getBytes());
	}

	private static String encodeMd5(byte[] source) {
		try {
			return encodeHex(MessageDigest.getInstance("MD5").digest(source));
		} catch (NoSuchAlgorithmException var2) {
			throw new IllegalStateException(var2.getMessage(), var2);
		}
	}

	private static String encodeHex(byte[] bytes) {
		StringBuffer buffer = new StringBuffer(bytes.length * 2);

		for (int i = 0; i < bytes.length; ++i) {
			if ((bytes[i] & 255) < 16) {
				buffer.append("0");
			}

			buffer.append(Long.toString((long) (bytes[i] & 255), 16));
		}

		return buffer.toString();
	}

	public static void main(String[] args) {
		//System.out.println(encrypt("123321"));
		System.out.println(getSalt());
	}
}
